<template>
  <div class="china-map-container">
    <div class="map-header">
      <h3 class="text-xl font-bold text-white mb-4">{{ ts('全国政策分布热力图', '全国政策分布热力图') }}</h3>
      <div class="legend">
        <div class="legend-item">
          <div class="legend-color" style="background: #bfdbfe"></div>
          <span>0-50</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #93c5fd"></div>
          <span>51-100</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #60a5fa"></div>
          <span>101-200</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #3b82f6"></div>
          <span>201-300</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #1e3a8a"></div>
          <span>300+</span>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div 
        ref="chinaMap" 
        class="china-map-chart"
        @mouseleave="handleMouseLeave"
        @click.self="closeTooltip"
      ></div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p class="loading-text">{{ ts('正在加载地图数据...', '正在加载地图数据...') }}</p>
      </div>
    </div>
    
    <!-- 省份详情弹窗 -->
    <div 
      v-if="selectedProvince && showTooltip" 
      class="province-detail"
      :style="{ left: tooltipX + 'px', top: tooltipY + 'px' }"
    >
      <div class="detail-header">
        <h4>{{ selectedProvince }}</h4>
        <button @click="closeTooltip" class="close-btn">×</button>
      </div>
      <div class="detail-content">
        <p>{{ ts('政策数量', '政策数量') }}: {{ selectedProvinceData?.count || 0 }}</p>
        <p>{{ ts('最新政策', '最新政策') }}: {{ selectedProvinceData?.latest || ts('暂无', '暂无') }}</p>
        <p>{{ ts('更新时间', '更新时间') }}: {{ selectedProvinceData?.updateTime || '2024-01-15' }}</p>
        <div ref="trendChart" class="trend-chart" v-show="showTooltip"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { useTranslation } from '../composables/useTranslation.js'

export default {
  name: 'ChinaMapSVG',
  setup() {
    // 使用翻译系统
    const { ts } = useTranslation()

    return {
      ts
    }
  },
  data() {
    return {
      chart: null,
      loading: true,
      selectedProvince: null,
      showTooltip: false,
      tooltipX: 0,
      tooltipY: 0,
      provinceData: {
        '北京市': { count: 245, latest: '关于优化营商环境的实施意见', updateTime: '2024-01-15' },
        '上海市': { count: 198, latest: '上海市数字化转型实施方案', updateTime: '2024-01-14' },
        '广东省': { count: 312, latest: '广东省制造业高质量发展规划', updateTime: '2024-01-13' },
        '江苏省': { count: 287, latest: '江苏省科技创新支持政策', updateTime: '2024-01-12' },
        '浙江省': { count: 234, latest: '浙江省数字经济发展纲要', updateTime: '2024-01-11' },
        '山东省': { count: 276, latest: '山东省新旧动能转换政策', updateTime: '2024-01-10' },
        '河南省': { count: 189, latest: '河南省乡村振兴实施方案', updateTime: '2024-01-09' },
        '湖北省': { count: 167, latest: '湖北省产业升级指导意见', updateTime: '2024-01-08' },
        '湖南省': { count: 156, latest: '湖南省创新驱动发展战略', updateTime: '2024-01-07' },
        '四川省': { count: 203, latest: '四川省西部大开发政策', updateTime: '2024-01-06' },
        '河北省': { count: 145, latest: '河北省协同发展实施方案', updateTime: '2024-01-05' },
        '福建省': { count: 134, latest: '福建省海丝核心区建设规划', updateTime: '2024-01-04' },
        '安徽省': { count: 123, latest: '安徽省长三角一体化政策', updateTime: '2024-01-03' },
        '陕西省': { count: 112, latest: '陕西省丝路经济带建设方案', updateTime: '2024-01-02' },
        '江西省': { count: 98, latest: '江西省绿色发展实施意见', updateTime: '2024-01-01' },
        '重庆市': { count: 87, latest: '重庆市内陆开放高地建设', updateTime: '2023-12-31' },
        '辽宁省': { count: 156, latest: '辽宁省振兴发展实施方案', updateTime: '2023-12-30' },
        '天津市': { count: 134, latest: '天津市京津冀协同发展规划', updateTime: '2023-12-29' },
        '云南省': { count: 89, latest: '云南省面向南亚东南亚开放', updateTime: '2023-12-28' },
        '山西省': { count: 76, latest: '山西省能源革命综合改革', updateTime: '2023-12-27' },
        '广西壮族自治区': { count: 95, latest: '广西北部湾经济区发展规划', updateTime: '2023-12-26' },
        '吉林省': { count: 65, latest: '吉林省东北振兴实施方案', updateTime: '2023-12-25' },
        '贵州省': { count: 54, latest: '贵州省大数据发展战略', updateTime: '2023-12-24' },
        '甘肃省': { count: 43, latest: '甘肃省丝路经济带建设', updateTime: '2023-12-23' },
        '内蒙古自治区': { count: 78, latest: '内蒙古现代能源经济发展', updateTime: '2023-12-22' },
        '海南省': { count: 67, latest: '海南自贸港建设总体方案', updateTime: '2023-12-21' },
        '黑龙江省': { count: 56, latest: '黑龙江省现代农业发展规划', updateTime: '2023-12-20' },
        '宁夏回族自治区': { count: 32, latest: '宁夏内陆开放型经济试验区', updateTime: '2023-12-19' },
        '青海省': { count: 28, latest: '青海省生态文明建设规划', updateTime: '2023-12-18' },
        '新疆维吾尔自治区': { count: 45, latest: '新疆丝绸之路经济带建设', updateTime: '2023-12-17' },
        '西藏自治区': { count: 23, latest: '西藏自治区发展实施方案', updateTime: '2023-12-16' },
        '台湾省': { count: 0, latest: '暂无', updateTime: '暂无' },
        '香港特别行政区': { count: 89, latest: '香港特区发展规划纲要', updateTime: '2023-12-15' },
        '澳门特别行政区': { count: 45, latest: '澳门特区多元发展规划', updateTime: '2023-12-14' }
      },
      trendData: {
        '北京市': [180, 195, 205, 215, 225, 235, 245],
        '上海市': [150, 160, 170, 180, 188, 193, 198],
        '广东省': [260, 270, 280, 290, 295, 305, 312],
        '江苏省': [230, 240, 250, 260, 270, 278, 287],
        '浙江省': [180, 190, 200, 210, 218, 225, 234],
        '山东省': [220, 230, 240, 250, 260, 268, 276],
        '河南省': [140, 150, 160, 170, 178, 184, 189],
        '湖北省': [120, 130, 140, 150, 158, 163, 167],
        '湖南省': [110, 120, 130, 140, 148, 152, 156],
        '四川省': [150, 160, 170, 180, 190, 198, 203],
        '河北省': [100, 110, 120, 130, 138, 143, 145],
        '福建省': [90, 100, 110, 120, 126, 130, 134],
        '安徽省': [80, 90, 100, 110, 115, 120, 123],
        '陕西省': [70, 80, 90, 100, 105, 108, 112],
        '江西省': [60, 70, 80, 85, 90, 95, 98],
        '重庆市': [60, 65, 70, 75, 80, 85, 87],
        '辽宁省': [110, 120, 130, 140, 145, 150, 156],
        '天津市': [90, 100, 110, 120, 125, 130, 134],
        '云南省': [60, 70, 75, 80, 84, 87, 89],
        '山西省': [50, 55, 60, 65, 70, 74, 76],
        '广西壮族自治区': [60, 65, 70, 80, 85, 90, 95],
        '吉林省': [40, 45, 50, 55, 60, 63, 65],
        '贵州省': [30, 35, 40, 45, 50, 52, 54],
        '甘肃省': [25, 28, 32, 36, 40, 42, 43],
        '内蒙古自治区': [50, 55, 60, 65, 70, 75, 78],
        '海南省': [50, 55, 58, 60, 63, 65, 67],
        '黑龙江省': [40, 45, 48, 50, 52, 54, 56],
        '宁夏回族自治区': [20, 22, 25, 28, 30, 31, 32],
        '青海省': [15, 18, 20, 22, 25, 27, 28],
        '新疆维吾尔自治区': [30, 35, 38, 40, 42, 44, 45],
        '西藏自治区': [15, 17, 18, 19, 20, 22, 23],
        '台湾省': [0, 0, 0, 0, 0, 0, 0],
        '香港特别行政区': [60, 65, 70, 75, 80, 85, 89],
        '澳门特别行政区': [30, 33, 36, 39, 42, 44, 45]
      }
    }
  },
  computed: {
    selectedProvinceData() {
      return this.provinceData[this.selectedProvince]
    }
  },
  mounted() {
    this.initMap()
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    async initMap() {
      try {
        // 动态加载 ECharts
        const echarts = await this.loadECharts()
        
        // 获取中国地图数据
        const chinaGeoData = await this.loadChinaMapData()
        
        // 注册地图
        echarts.registerMap('china', chinaGeoData)
        
        // 初始化图表
        this.chart = echarts.init(this.$refs.chinaMap, 'dark')
        
        // 配置图表选项
        const option = this.getMapOption()
        this.chart.setOption(option)
        
        // 绑定事件
        this.bindEvents()
        
        this.loading = false
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.loading = false
      }
    },
    
    async loadECharts() {
      return new Promise((resolve, reject) => {
        if (window.echarts) {
          resolve(window.echarts)
          return
        }
        
        const script = document.createElement('script')
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js'
        script.onload = () => resolve(window.echarts)
        script.onerror = reject
        document.head.appendChild(script)
      })
    },
    
    async loadChinaMapData() {
      const response = await fetch('https://geo.datav.aliyun.com/areas/bound/100000_full.json')
      if (!response.ok) {
        throw new Error('Failed to load map data')
      }
      return await response.json()
    },

    renderTrendChart() {
    const echarts = window.echarts;
    if (!echarts || !this.selectedProvince) return;

    const chartDom = this.$refs.trendChart;
    const trendChart = echarts.init(chartDom);

    const data = this.trendData[this.selectedProvince] || [];
    const months = ['6', '7', '8', '9', '10', '11', '12'];

    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const value = params[0]?.value || 0;
          return `${this.ts('月份', '月份')}: ${params[0]?.name}<br>${this.ts('政策数量', '政策数量')}: ${value}`;
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '8%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLine: { lineStyle: { color: '#ccc' } },
        axisLabel: { color: '#e2e8f0' }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#ccc' } },
        splitLine: { lineStyle: { color: '#334155' } },
        axisLabel: { color: '#e2e8f0' }
      },
      series: [
        {
          name: this.ts('政策数量', '政策数量'),
          type: 'line',
          data: data,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: '#00f5ff',
            width: 2
          },
          itemStyle: {
            color: '#00f5ff'
          },
          areaStyle: {
            color: 'rgba(0, 245, 255, 0.1)'
          }
        }
      ]
    };

    trendChart.setOption(option);
  },
    
    getMapOption() {
      // 准备数据
      const mapData = Object.keys(this.provinceData).map(name => ({
        name,
        value: this.provinceData[name].count
      }))
      
      return {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const data = this.provinceData[params.name]
            if (!data) return `${params.name}<br/>${this.ts('暂无数据', '暂无数据')}`
            return `
              <div style="padding: 8px;">
                <div style="font-weight: bold; color: #00f5ff; margin-bottom: 8px;">${params.name}</div>
                <div style="margin-bottom: 4px;">${this.ts('政策数量', '政策数量')}: <span style="color: #00f5ff;">${data.count}</span></div>
                <div style="margin-bottom: 4px;">${this.ts('最新政策', '最新政策')}: ${data.latest}</div>
                <div>${this.ts('更新时间', '更新时间')}: ${data.updateTime}</div>
              </div>
            `
          },
          backgroundColor: 'rgba(15, 23, 42, 0.95)',
          borderColor: 'rgba(0, 245, 255, 0.3)',
          borderWidth: 1,
          textStyle: {
            color: '#e2e8f0',
            fontSize: 12
          }
        },
        visualMap: {
          min: 0,
          max: 350,
          left: 'left',
          top: 'bottom',
          text: [this.ts('高', '高'), this.ts('低', '低')],
          realtime: false,
          calculable: false,
          inRange: {
            color: ['#bfdbfe', '#93c5fd', '#60a5fa', '#3b82f6', '#1e3a8a']
          },
          textStyle: {
            color: '#e2e8f0'
          }
        },
        series: [
          {
            name: this.ts('政策数量', '政策数量'),
            type: 'map',
            map: 'china',
            roam: true,
            zoom: 1.2,
            scaleLimit: {
              min: 0.8,
              max: 3
            },
            emphasis: {
              focus: 'self',
              itemStyle: {
                areaColor: '#00f5ff',
                borderColor: '#ffffff',
                borderWidth: 2,
                shadowColor: 'rgba(0, 245, 255, 0.8)',
                shadowBlur: 10
              },
              label: {
                show: true,
                color: '#000',
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            select: {
              itemStyle: {
                areaColor: '#00f5ff'
              },
              label: {
                show: true,
                color: '#000',
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            itemStyle: {
              borderColor: 'rgba(0, 245, 255, 0.3)',
              borderWidth: 1,
              shadowColor: 'rgba(0, 0, 0, 0.3)',
              shadowBlur: 3
            },
            label: {
              show: false,
              color: '#e2e8f0',
              fontSize: 10
            },
            data: mapData
          }
        ]
      }
    },
    
    bindEvents() {
  // 点击事件
  this.chart.on('click', (params) => {
    if (params.componentType === 'series') {
      this.selectedProvince = params.name;
      this.showTooltip = true;
      this.updateTooltipPosition(params.event.event);
      this.$nextTick(() => {
        this.renderTrendChart(); // 渲染折线图
      });
    }
  });

  // 鼠标移动事件
  this.chart.on('mousemove', (params) => {
    if (params.componentType === 'series') {
      this.updateTooltipPosition(params.event.event);
    }
  });

  // 窗口大小变化
  window.addEventListener('resize', this.handleResize);
},
    
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    
    handleMouseLeave() {
      // 可以在这里处理鼠标离开地图的逻辑
    },
    
    updateTooltipPosition(event) {
      const rect = this.$refs.chinaMap.getBoundingClientRect()
      this.tooltipX = event.clientX - rect.left + 10
      this.tooltipY = event.clientY - rect.top - 10
    },
    
    closeTooltip() {
      this.showTooltip = false
      this.selectedProvince = null
    }
  }
}
</script>

<style scoped>
.china-map-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.legend {
  display: flex;
  gap: 15px;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #94a3b8;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.map-container {
  position: relative;
  width: 100%;
  height: 500px;
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.8) 0%, rgba(30, 41, 59, 0.6) 100%);
  border-radius: 12px;
  border: 1px solid rgba(0, 245, 255, 0.2);
  overflow: hidden;
}

.china-map-chart {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(15, 23, 42, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 245, 255, 0.3);
  border-top: 3px solid #00f5ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  color: #00f5ff;
  font-size: 14px;
  margin: 0;
}

.trend-chart {
    width: 100%;
    height: 150px;
    margin-top: 10px;
  }

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.province-detail {
  position: absolute;
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.95) 0%, rgba(30, 41, 59, 0.95) 100%);
  border: 1px solid rgba(0, 245, 255, 0.3);
  border-radius: 8px;
  padding: 15px;
  min-width: 200px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  pointer-events: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(0, 245, 255, 0.2);
}

.detail-header h4 {
  color: #00f5ff;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #94a3b8;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.detail-content p {
  margin: 8px 0;
  color: #e2e8f0;
  font-size: 14px;
  line-height: 1.4;
}

.detail-content p:first-child {
  color: #00f5ff;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .legend {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .legend-item {
    font-size: 11px;
  }
  
  .map-container {
    height: 400px;
  }
  
  .province-detail {
    max-width: 250px;
    font-size: 13px;
  }

}
</style> 